local VERSION = tonumber(("$Revision: 179 $"):match("%d+"))

local _G = getfenv(0)

local L = AceLibrary("AceLocale-2.2"):new("AuldLangSyne_Backup")

local AuldLangSyne = AuldLangSyne
local Backup
if AuldLangSyne then
	Backup = AuldLangSyne:NewModule("Backup", "AceConsole-2.0")
	if AuldLangSyne.revision < VERSION then
		AuldLangSyne.version = "r" .. VERSION
		AuldLangSyne.revision = VERSION
		AuldLangSyne.date = ("$Date: 2007-10-01 00:36:40 +0000 (Mon, 01 Oct 2007) $"):match("%d%d%d%d%-%d%d%-%d%d")
	end
else
	Backup = AceLibrary("AceAddon-2.0"):new("AceConsole-2.0", "AceDB-2.0")
	AuldLangSyne_Backup = Backup -- since this isn't a module in this branch, global for access
end

local function clear(t)
	for k in pairs(t) do
		t[k] = nil
	end
	t[''] = true
	t[''] = nil
	return t
end

function Backup:OnInitialize(name)
	local chardefaults = {
		friends = {
			["*"] = {},
		},
	}
	if AuldLangSyne then
		self.db = AuldLangSyne:AcquireDBNamespace("Backup")
		AuldLangSyne:RegisterDefaults("Backup", "char", chardefaults)
	else
		self:RegisterDB("AuldLangSyneBackupDB")
		self:RegisterDefaults("char", chardefaults)
	end
	
	self.menu = {
		handler = Backup,
		name = L["Backup"], type = "group",
		desc = L["Options for backing up and restoring your friends list"],
		args = {
			save = {
				name = L["Save"], type = "text", get = false,
				desc = L["Take a snapshot of your current friends list"],
				set = "SaveFriends", validate = {"1","2","3","4","5"},
			},
			load = {
				name = L["Load"], type = "text", get = false,
				desc = L["Restore a snapshot of your friends list, wiping out your current friends list"],
				set = "LoadFriends", validate = {"1","2","3","4","5","undo"},
			},
		},
	}
	
	self:RegisterChatCommand({'/backup', '/alsbackup',}, self.menu)
	
	if AuldLangSyne and AuldLangSyne.db.char.friends then
		--Import data from pre-modular.
		self.db.char.friends = AuldLangSyne.db.char.friends
		AuldLangSyne.db.char.friends = nil
	end
	
	self.undo = {}
end

------------------------------------------------------------------------
-- Backup
------------------------------------------------------------------------

function Backup:SaveFriends(slotnum)
	local slot
	if slotnum == "undo" then
		slot = clear(self.undo())
	else
		slot = clear(self.db.char.friends[slotnum])
	end
	for i=1, GetNumFriends() do
		local name, level, class, area, connected, status = GetFriendInfo(i)
		table.insert(slot, name)
	end
	self:Print(format(L["Backed up %d friends to slot %d"], GetNumFriends(), slotnum))
end

function Backup:LoadFriends(slotnum)
	local slot
	if slotnum == "undo" then
		slot = self.undo
	else
		slot = self.db.char.friends[slotnum]
	end
	if table.getn(slot) > 0 then
		for i=1, GetNumFriends() do
			RemoveFriend(i)
		end
		for _,name in pairs(slot) do
			AddFriend(name)
		end
	else
		self:Print(L["This slot is currently empty."])
	end
end
